import {loginByName, logout, getUserInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'

const user = {
	state: {
		user: '',
		status: '',
		code: '',
		token: getToken(),
		name: '',
		avatar: '',
		introduction: '',
		roles: [],
		perms: [],
		setting: {
			articlePlatform: []
		}
	},
	mutations: {
		SET_CODE: (state, code) => {
			state.code = code
		},
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_INTRODUCTION: (state, introduction) => {
			state.introduction = introduction
		},
		SET_SETTING: (state, setting) => {
			state.setting = setting
		},
		SET_STATUS: (state, status) => {
			state.status = status
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		},
		SET_PERMS: (state, perms) => {
			state.perms = perms
		}
	},
	actions: {
		// 用户名登录
		loginByName({commit}, userInfo) {
			return new Promise((resolve, reject) => {
				loginByName(userInfo.loginName, userInfo.password).then(res => {
					const data = res.data
					setToken(data.token)
					commit('SET_TOKEN', data.token)
					commit('SET_PERMS', data.menuList)
					commit('SET_ROLES', data.admin.type)
					commit('SET_NAME', data.admin.nickName)
					commit('SET_AVATAR', data.admin.imageUrl)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetUserInfo({commit, state}) {
			return new Promise((resolve, reject) => {
				getUserInfo(state.token).then(res => {
					const data = res.data
					commit('SET_PERMS', data.menuList)
					commit('SET_ROLES', data.admin.type)
					commit('SET_NAME', data.admin.nickName)
					commit('SET_AVATAR', data.admin.imageUrl)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登出
		LogOut({commit, state}) {
			return new Promise((resolve, reject) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_ROLES', [])
					commit('SET_PERMS', [])
					removeToken()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 前端 登出
		FedLogOut({commit}) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				removeToken()
				resolve()
			})
		}
	}
}
export default user
